其他
老程序员为什么从不使用 Java 自带的序列化?
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
关注公众号后台回复pay或mall获取实战项目资料+视频
作者:rickiyang
原文:www.cnblogs.com/rickiyang/p/11074232.html
@Test
public void testSerializable(){
String str = "哈哈,我是一条消息";
Message msg = new Message((byte)0xAD,35,str);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(msg);
os.flush();
byte[] b = out.toByteArray();
System.out.println("jdk序列化后的长度: "+b.length);
os.close();
out.close();
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] bt = msg.getMsgBody().getBytes();
buffer.put(msg.getType());
buffer.putInt(msg.getLength());
buffer.put(bt);
buffer.flip();
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
System.out.println("使用二进制序列化的长度:"+result.length);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testSerializable(){
String str = "哈哈,我是一条消息";
Message msg = new Message((byte)0xAD,35,str);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
long startTime = System.currentTimeMillis();
for(int i = 0;i < 100000;i++){
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(msg);
os.flush();
byte[] b = out.toByteArray();
/*System.out.println("jdk序列化后的长度: "+b.length);*/
os.close();
out.close();
}
long endTime = System.currentTimeMillis();
System.out.println("jdk序列化100000次耗时:" +(endTime - startTime));
long startTime1 = System.currentTimeMillis();
for(int i = 0;i < 100000;i++){
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] bt = msg.getMsgBody().getBytes();
buffer.put(msg.getType());
buffer.putInt(msg.getLength());
buffer.put(bt);
buffer.flip();
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
/*System.out.println("使用二进制序列化的长度:"+result.length);*/
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用二进制序列化100000次耗时:" +(endTime1 - startTime1));
} catch (IOException e) {
e.printStackTrace();
}
}
有热门推荐👇
10个解放双手的 IDEA 插件,这些代码千万别再用手写了,直接生成!
刚刚用鸿蒙跑了个“hello world”!跑通后,我特么开始怀疑人生了....
SpringBoot整合Redis+mybatis,封装RedisUtils工具类等实战(附源码)
点击阅读原文,前往学习SpringCloud实战项目